<template>
  <div class="app-container">
    <el-form ref="form"
             :model="queryForm"
             label-width="80px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="处理编号">
            <el-input v-model="queryForm.noticeId"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司名称">
            <el-input v-model="queryForm.companyName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车牌">
            <span style="width: 80px; float: left;">
              <el-select v-model="queryForm.tidNgenColor"
                         placeholder="">
                <el-option v-for="item in vehicleColor"
                           :key="item.id"
                           :label="item.value"
                           :value="item.id">
                </el-option>
              </el-select>
            </span>
            <span style="width: 70px; float: left; margin-left: 10px;">
              <el-input v-model="queryForm.tidNgenPy"></el-input>
            </span>
            <span style="width: 125px; float: left; margin-left: 10px;">
              <el-input v-model="queryForm.tidNgenKey"></el-input>
            </span>
            <span style="width: 50px; float: left; margin-left: 10px;">
              <el-select style="width:100px"
                         v-model="queryForm.tidNgenSuf"
                         placeholder="">
                <el-option v-for="item in vehicleSuf"
                           :key="item.id"
                           :label="item.value"
                           :value="item.id">
                </el-option>
              </el-select>
            </span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="开始时间">
            <el-date-picker v-model="queryForm.startTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            style="width: 100%"
                            :clearable="false"
                            placeholder="">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束时间">
            <el-date-picker v-model="queryForm.endTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            style="width: 100%"
                            :clearable="false"
                            placeholder="">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="PCC卡号">
            <el-input v-model="queryForm.pcc"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label-width="120px"
                        label="司机联系电话">
            <el-input v-model="queryForm.manTel"></el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="使用次数">
            <el-input type='number'
                      :min="0"
                      oninput="if(value<0)value=0"
                      v-model="queryForm.times"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否已使用"
                        label-width="90px">
            <el-select v-model="queryForm.status"
                       placeholder="">
              <el-option v-for="item in status"
                         :key="item.id"
                         :label="item.value"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用原因"
                        label-width="90px">
            <el-select style="width: 100%"
                       v-model="queryForm.reason"
                       placeholder="">
              <el-option v-for="item in reason"
                         :key="item.id"
                         :label="item.value"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="14">
          <el-button :disabled="$props.custom.saveExcelDisable"
                     @click="saveExcel"
                     type="primary">另存EXCEL</el-button>
        </el-col>
        <el-col :span="10">
          <el-form-item label=""
                        label-width="20px">
            <div style="float: right">
              <el-button @click="search"
                         type="primary">查询</el-button>
              <el-button @click="reset"
                         type="primary">重置</el-button>
              <el-button type="warning"
                         @click="logout">返回</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <el-col :span="24">
        <!-- @row-click="editRow" -->
        <el-table :data="tableData"
                  border
                  height="370px"
                  style="width: 100%">
          <el-table-column type="index"
                           label="行号"
                           width="50">
          </el-table-column>
          <el-table-column prop="idNoticeId"
                           align="center"
                           label="编号"
                           width="80">
          </el-table-column>
          <el-table-column prop="fullName"
                           align="center"
                           show-overflow-tooltip
                           label="公司名称">
          </el-table-column>
          <el-table-column align="center"
                           label="车牌"
                           width="100">
            <template slot-scope="scope">
              {{scope.row.tidNgenColor}} | {{scope.row.tidNgenPy}} | {{scope.row.tidNgenKey}} | {{scope.row.tidNgenSuf}}
            </template>
          </el-table-column>
          <el-table-column prop="tcCode"
                           align="center"
                           label="PCC卡号"
                           width="80">
          </el-table-column>
          <el-table-column align="center"
                           width="120"
                           label="创建日期">
            <template slot-scope="scope">
              <span>{{formatDateTime(scope.row.recordTime)}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           width="120"
                           label="是否已使用">
            <template slot-scope="scope">
              <span v-if="scope.row.status === '01'">未使用</span>
              <span v-else-if="scope.row.status === '02'">已使用</span>
              <span v-else-if="scope.row.status === '03'">作废</span>
            </template>
          </el-table-column>
          <el-table-column prop="manTel"
                           align="center"
                           width="130"
                           label="司机联系电话" />
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>
<script>
const xlsx = require("node-xlsx")
const fs = require("fs")
import { ipcRenderer } from 'electron'
import { GSAConstants } from '@/utils/access'
import { formatDate, parseDate } from '@/utils/date'
import {
  showWarningMsg,
  showSuccessMsg,
  log
} from '@/utils/message'

export default {
  props: {
    custom: {
      type: Object,
      default: function () {
        return {}
      }
    },
    title: {
      type: String,
      default: function () {
        return ''
      }
    }, ic: {
      type: String,
      default: function () {
        return ''
      }
    },
    url: {
      type: String,
      default: function () {
        return ''
      }
    },
  },
  data () {
    return {
      path: '',
      msgInter: null,
      showMessage: {
        msg: '请刷卡......',
        success: false,
        type: 'success',
        mession: '您的交柜未进行PAS申报(验箱的箱号未进行PAS申报)，请核查PAS申报资料',
        tips: '请不要在飞仔未打印完毕时拉扯飞仔纸,以免导致卡纸'
      },
      multipleSelection: [],
      tableData: [],
      vehicleSuf: [
        { id: '', value: '' },
        { id: '港', value: '港' },
        { id: '澳', value: '澳' }
      ],
      vehicleColor: [
        { id: '', value: '' },
        { id: '蓝', value: '蓝' },
        { id: '黑', value: '黑' },
        { id: '绿', value: '绿' },
        { id: '红', value: '红' },
        { id: '黄', value: '黄' },
        { id: '白', value: '白' }
      ],
      status: [
        { id: '', value: '' },
        { id: '01', value: '未使用' },
        { id: '02', value: '已使用' },
        { id: '03', value: '作废' }
      ],
      reason: [
        { id: '', value: '' },
        { id: '无PCC卡', value: '无PCC卡' },
        { id: '无身份证明证件', value: '无身份证明证件' },
        { id: '无效PCC卡', value: '无效PCC卡' },
        { id: '无效身份证明证件', value: '无效身份证明证件' },
        { id: '违章车辆', value: '违章车辆' },
        { id: '被锁车辆', value: '被锁车辆' },
        { id: '黑名单车辆', value: '黑名单车辆' },
        { id: '黑名单司机', value: '黑名单司机' },
        { id: '无从业资格证司机', value: '无从业资格证司机' },
        { id: '已注销车辆', value: '已注销车辆' },
        { id: '无年审车辆', value: '无年审车辆' },
      ],
      queryForm: {
        companyName: '',
        times: '',
        noticeId: '',
        tidNgenColor: '',
        tidNgenPy: '',
        tidNgenKey: '',
        tidNgenSuf: '',
        tcCode: '',
        reason: '',
        status: '',
        manTel: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        total: 1
      },
      form: {
        name: '',
        idNo: '',
        saltIdNo: '',
        tractorNo: '',
        saltName: '',
        pccId: '',
        permitNo: '',
      }
    }
  },
  created () {
    this.init()
  },
  mounted () {
  },
  methods: {
    init () {
      // 获取一周前日期
      let start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      start.setMinutes(0)
      start.setHours(0)
      this.queryForm.startTime = formatDate(start)

      let end = new Date();
      end.setMinutes(59)
      end.setHours(23)
      this.queryForm.endTime = formatDate(end)
    },
    // 转换日期 
    formatDateTime (timestrap) {
      if (!timestrap) {
        return ''
      }
      return formatDate(new Date(timestrap))
    },
    // 选中行
    handleSelectionChange (val) {
      this.multipleSelection = val;
      log('检测到行被选中', val)
    },
    // 另存EXCEL
    saveExcel () {
      if (this.tableData.length === 0) {
        showWarningMsg('请先进行查询')
        return
      }
      // 打开文件夹选择器， 选择后会通过事件回掉回来， 然后执行 genExcel
      this.browseFolder()
    },
    // 选择文件夹
    browseFolder () {
      ipcRenderer.send('open-dir-check-dialog')
    },
    // 父页面加载完成会调用注册监听
    registerListener () {
      log('挂载选择文件夹监听事件')
      ipcRenderer.on('open-dir-check-dialog-reply', (event, path) => {
        this.path = path
        this.genExcel(path, this.tableData)
      })
    },
    // 编辑行
    editRow () {
      if (this.multipleSelection.length === 0) {
        showWarningMsg('最少选择一行需要被编辑的行')
        return
      }
      if (this.multipleSelection.length > 1) {
        showWarningMsg('最多只能编辑一行')
        return
      }
      const row = this.multipleSelection[0]

      // 校验
      if (row.taskStatus === '03') {
        showWarningMsg('已出闸记录不能修改！')
        return
      }
      if (row.taskStatus === '04') {
        showWarningMsg('无效入闸记录不能修改！')
        return
      }
      if (row.bindStatus === '04' || row.bindStatus === '03') {
        showWarningMsg('已作废记录不能修改！')
        return
      }
      if (row.bindStatus === '01') {
        showWarningMsg('未绑定记录不能修改！')
        return
      }


      log('检测到行被点击', row)
      const editForm = this.parseEditForm(row)
      log('转换行数据', editForm)
      // this.$store.commit('SET_CAR_EDIT_ROW', row)
      // log('测试从数据池中获取数据', this.$store.getters.carEditRow)
      this.$refs.editOsd.show(editForm)

      // 更新核心的数据包
      this.setParentForm(editForm)

      // 更新渲染页面
      this.setForm(editForm)

    },
    // 行数据转换成编辑表单需要的数据
    parseEditForm (row) {
      return {
        transid: row.transId,
        tcCode: row.tcCode,
        pccId: row.tcCode,
        companyName: row.companyName,
        returnReceiptId: row.returnReceiptId,
        //  "无PCC卡", "PCC卡已坏", "无效身份证", "使用第一代身份证", "使用港澳身份证",
        // "使用驾驶证", "使用从业资格证", "无任何证件", "其他" 
        reason: row.bindReason,
        hasPcc: row.hasPccCard,
        hasId: row.hasIdCard,
        idName: row.idName,
        manTel: row.manTel,
        driverCardId: row.idNumber,
        // "蓝", "黑", "绿", "红", "黄", "白"
        vehicleColor: row.tidNgenColor,
        vehiclePy: row.tidNgenPy,
        vehicleKey: row.tidNgenKey,
        // "", "港", "澳" 
        vehicleSuf: row.tidNgenSuf
      }

    },
    searchValidate () {
      //限制查询时间 一个月
      const isZero = this.queryForm.times === 0 || this.queryForm.times === '0'
      const startTime = parseDate(this.queryForm.startTime)
      const endTime = parseDate(this.queryForm.endTime)
      const startTime_ = startTime.getTime()
      const endTime_ = endTime.getTime()

      // 计算日期差
      const subTime = endTime_ - startTime_
      if (subTime < 0) {
        showWarningMsg('查询结束时间必须大于开始时间')
        return
      }
      const subDays = subTime / (1000 * 3600 * 24)
      if (this.isBlank(this.queryForm.noticeId) && this.isBlank(this.queryForm.tidNgenKey)
        && this.isBlank(this.queryForm.tcCode) && isZero) {
        if (subDays > 31) {
          showWarningMsg(this.queryForm.startTime + ' 和 ' + this.queryForm.endTime
            + '必须在一个月以内')
          return false
        }
      } else {
        // 限制查询时间 一年
        log('subDays', subDays)
        if (subDays > 365) {
          showWarningMsg(this.queryForm.startTime + ' 和 ' + this.queryForm.endTime
            + '必须在一年以内')
          return false
        }
      }

      return true
    },
    readCard (type) {
      this.$emit('readCard', type)
    },
    reset () {
      this.queryForm = {
        companyName: '',
        times: '',
        noticeId: '',
        tidNgenColor: '',
        tidNgenPy: '',
        tidNgenKey: '',
        tidNgenSuf: '',
        tcCode: '',
        reason: '',
        status: '',
        manTel: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        total: 1
      }
      this.init()

    },
    isBlank (str) {
      return str === undefined || str.trim() === ''
    },
    // search
    search () {
      //限制查询时间 一个月
      if (!this.searchValidate()) {
        return
      }


      let message = {
        dt: this.queryForm,
        ic: this.$props.ic,
        en: false
      }
      log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', this.$props.url, message)
      this.$emit('customSentMqttMsg', this.$props.url, message)
    },
    // 连接MQTT回掉
    connectSuccess (res) {
      // 执行搜索
      this.search()
    },
    showMsg (dt) {
      this.showMessage.msg = dt.msg
      this.showMessage.type = dt.type
      let type = ''
      if (dt.type === 'error') {
        type = 'error'
      } else if (dt.type === 'green') {
        type = 'success'
      } else {
        type = 'info'
      }

      if (this.msgInter) {
        clearTimeout(this.msgInter)
      }
      this.msgInter = setTimeout(() => {
        this.$message({
          message: dt.msg,
          type: type
        })
      }, 1000)
    },
    setParentForm (form) {
      this.$emit('setForm', form)
    },
    logout () {
      this.$emit('logout')
    },
    // 读PCC卡回写的函数
    setForm (form) {
      this.$refs.editOsd.doMethod('setForm', form)
    },
    // 读ID成功
    readIcCardSuccess (res) {
      this.$refs.editOsd.doMethod('readIcCardSuccess', res)
    },
    // 读ID成功
    readIdCardSuccess (res) {
      this.$refs.editOsd.doMethod('readIdCardSuccess', res)
    },
    // 生成excel的核心方法
    genExcel (path, data) {
      log('genEXCEL', data)

      const list = [
        {
          name: "sheet",
          data: this.getExportData(data)
        },
      ];

      const buffer = xlsx.build(list);
      fs.writeFile(path + '\\data_' + new Date().getTime() + '.xlsx', buffer, function (err) {
        if (err) {
          log(err, "保存excel出错");
        } else {
          log("写入excel成功!!!");
          showSuccessMsg('导出成功！')
        }
      })
    },
    // 导出excel的方法
    getExportData (lists) {
      const data = []

      // 先存入表头
      data[0] = ['编号', '公司名称', '车牌', 'PCC卡号', '创建日期', '是否已使用', '司机联系电话']

      let i = 0
      lists.forEach(row => {
        let status = ''
        if (row.status === '01') {
          status = '未使用'
        } else if (row.status === '02') {
          status = '已使用'
        } else if (row.status === '03') {
          status = '作废'
        }

        data[++i] = [
          row.idNoticeId,
          row.fullName,
          row.tidNgenColor + '|' + row.tidNgenPy + '|' + row.tidNgenKey + '|' + (row.tidNgenSuf !== undefined ? row.tidNgenSuf : ''),
          row.tcCode,
          this.formatDateTime(row.recordTime),
          status,
          row.manTel
        ]
      })

      return data
    },
    // mqtt 消息回掉
    handleSuccessMqttMessage (messageObject) {
      log('接收到系统返回数据， 准备渲染数据', messageObject)
      if (messageObject.ic === GSAConstants().TOPIC_QUERY_ID_NOTICE.ic) {
        this.tableData = messageObject.dt.data
        this.queryForm.currentPage = messageObject.dt.currentPage
        this.queryForm.total = messageObject.dt.total
      } else if (messageObject.ic === GSAConstants().TOPIC_PRINT_CMS.ic) {
        log('重印CMS成功')
        showSuccessMsg('重印CMS成功')
      }
    },
  },
}
</script>

<style scoped>
.app-container >>> .el-input {
  font-size: 18px;
}

.app-container >>> .el-checkbox__inner {
  border: 1px solid #000000;
}
</style>
